package cn.spream.dream.web.controller;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 视图控制层
 * Created with IntelliJ IDEA.
 * User: sjx
 * Date: 13-6-3
 * Time: 下午10:15
 * To change this template use File | Settings | File Templates.
 */
public abstract class BaseController extends AbstractController {

    //重定向返回结果前缀
    protected final static String REDIRECT = "redirect:";
    //转发返回结果前缀
    protected final static String FORWARD = "forward:";
    //controller请求地址后缀
    protected final static String CONTROLLER_SUFFIX = ".html";

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        return null;
    }

    /**
     * 跳转指定的地址
     * 需要传递参数的可以添加到Model中，
     * RedirectView将自动把Model中的参数添加到url后
     *
     * @param url 可以是全路径也可以是controller
     * @return
     */
    protected String redirect(String url) {
        return REDIRECT + toUrl(url);
    }

    /**
     * 重定向
     *
     * @param url
     * @return
     */
    protected String forward(String url) {
        return FORWARD + toUrl(url);
    }

    /**
     * 补全url
     *
     * @param url
     * @return
     */
    private String toUrl(String url) {
        if (StringUtils.isNotBlank(url) && url.startsWith("/") && url.indexOf(CONTROLLER_SUFFIX) < 0) {
            url += CONTROLLER_SUFFIX;
        }
        return url;
    }

}
